package com.chen;

import java.net.DatagramPacket;
import java.net.DatagramSocket;

public class UDPServer {
    public static void main(String[] args) {
        // 实现UDP一发一收
        System.out.println("===服务端启动===");
        try(DatagramSocket socket = new DatagramSocket(9999)) {
            // 准备数据包接收数据
            byte[] buf = new byte[1024*64];
            DatagramPacket packet = new DatagramPacket(buf, buf.length);
            // 接收数据
            while (true) {
                socket.receive(packet);
                System.out.println("收到来自" + packet.getAddress().getHostAddress() + "的UDP数据包，"+"端口号："+packet.getPort());
                System.out.println("内容是：" + new String(packet.getData(),0,packet.getLength()));
                System.out.println("===========================================");
            }
        } catch (Exception e) {
            System.out.println("数据接收失败！");
            e.printStackTrace();
        }
    }
}
